package com.amumu.drama.admin.modules.order.service.impl;

import com.amumu.drama.admin.dto.OmsMoneyInfoParam;
import com.amumu.drama.admin.dto.OmsReceiverInfoParam;
import com.amumu.drama.admin.modules.order.service.OmsOrderService;
import com.amumu.drama.admin.utils.AdminUtils;
import com.amumu.drama.common.base.api.CommonPage;
import com.amumu.drama.common.constant.OperateTypeEnum;
import com.amumu.drama.common.constant.OrderTypeEnum;
import com.amumu.drama.common.base.dto.req.IdReq;
import com.amumu.drama.common.exception.Asserts;
import com.amumu.drama.common.modules.admin.dao.OmsOrderDao;
import com.amumu.drama.common.modules.admin.dao.OmsOrderOperateHistoryDao;
import com.amumu.drama.common.modules.admin.dto.OmsOrderDeliveryParam;
import com.amumu.drama.common.modules.admin.dto.OmsOrderQueryParam;
import com.amumu.drama.common.modules.delivery.dto.DeliveryStatusResp;
import com.amumu.drama.common.modules.delivery.dto.req.DeliveryHandleDTO;
import com.amumu.drama.common.modules.delivery.service.DeliveryService;
import com.amumu.drama.common.modules.order.dto.OmsOrderDetail;
import com.amumu.drama.common.modules.order.dto.req.*;
import com.amumu.drama.common.modules.order.dto.resp.OmsOrderDetailResp;
import com.amumu.drama.common.modules.order.dto.resp.OmsOrderQueryResp;
import com.amumu.drama.common.modules.order.manager.OrderManager;
import com.amumu.drama.common.modules.order.mapper.OmsOrderDetailRespMapping;
import com.amumu.drama.common.modules.order.mapper.OrderOperateHistoryRespMapping;
import com.amumu.drama.common.modules.order.service.OmsPortalOrderService;
import com.amumu.drama.common.modules.order.service.PaymentService;
import com.amumu.drama.common.modules.service.impl.payment.PaymentReq;
import com.amumu.drama.mapper.OmsOrderMapper;
import com.amumu.drama.mapper.OmsOrderOperateHistoryMapper;
import com.amumu.drama.model.OmsOrder;
import com.amumu.drama.model.OmsOrderExample;
import com.amumu.drama.model.OmsOrderOperateHistory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单管理Service实现类
 * Created by macro on 2018/10/11.
 */
@Slf4j
@Service
public class OmsOrderServiceImpl implements OmsOrderService {
    @Autowired
    private OmsOrderMapper orderMapper;
    @Autowired
    private OmsOrderDao orderDao;
    @Autowired
    private OmsOrderOperateHistoryDao orderOperateHistoryDao;
    @Autowired
    private OmsOrderOperateHistoryMapper orderOperateHistoryMapper;

    @Autowired
    private OmsPortalOrderService omsPortalOrderService;

    @Autowired
    private DeliveryService deliveryService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private OrderManager orderManager;

    @Override
    public List<OmsOrderQueryResp> list(OmsOrderQueryParam queryParam, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        return orderDao.getList(queryParam);
    }

    @Override
    public CommonPage<OmsOrderQueryResp> listOrder(OmsOrderQueryParam request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<OmsOrderQueryResp> list = orderDao.getList(request);
        return CommonPage.restPage(list);
    }

    /**
     * 强制接口充值更改为手工充值
     *
     * @param request
     */
    @Override
    public void forceInterfaceToManuel(IdReq request) {
        OmsOrder order = orderMapper.selectByPrimaryKey(request.getId());
        if (order == null) {
            log.error("orderId:{}", request.getId());
            Asserts.fail("订单不存在");
        }
        if (!OrderTypeEnum.INTERFACE_DELIVERY.getCode().equals(order.getOrderType()) &&
                !OrderTypeEnum.MANUAL2INTERFACE_DELIVERY.getCode().equals(order.getOrderType())) {
            Asserts.fail("订单类型错误,不能转手工订单");
        }
        orderManager.changeOrderType(order, null,
                OrderTypeEnum.INTERFACE2MANUAL_DELIVERY, OperateTypeEnum.ADMIN, AdminUtils.getCurrentAdmin().getAdminId());
    }

    /**
     * 手工发货
     *
     * @param request
     */
    @Override
    public void manualDelivery(AdminManualDeliveryReq request) {
        DeliveryHandleDTO deliveryHandleDTO = new DeliveryHandleDTO();
        deliveryHandleDTO.setDeliverySn(request.getDeliverySn());
        Long adminId = AdminUtils.getCurrentAdmin().getAdminId();
        deliveryService.delivery(request.getOrderId(), deliveryHandleDTO, OperateTypeEnum.ADMIN, adminId);
    }

    /**
     * 手工发货成功
     *
     * @param request
     */
    @Override
    public void manualDeliverySuccess(AdminDeliverySuccessReq request) {
        Long adminId = AdminUtils.getCurrentAdmin().getAdminId();
        deliveryService.deliverySuccess(request, OperateTypeEnum.ADMIN, adminId);
    }

    /**
     * 重试接口充值
     *
     * @param request
     */
    @Override
    public void retryInterfaceDelivery(AdminRetryInterfaceRechargeReq request) {
        Long adminId = AdminUtils.getCurrentAdmin().getAdminId();
        //手工装接口订单才能进行接口重试
        OmsOrderDetail detail = omsPortalOrderService.detail(request.getOrderId());
        DeliveryStatusResp resp = new DeliveryStatusResp();
        resp.setMsg(request.getFailReason());
        orderManager.changeOrderType(detail, resp, OrderTypeEnum.MANUAL2INTERFACE_DELIVERY, OperateTypeEnum.ADMIN, AdminUtils.getCurrentAdmin().getAdminId());
        deliveryService.delivery(request.getOrderId(), null, OperateTypeEnum.ADMIN, adminId);
    }


    /**
     * 退款
     *
     * @param request
     */
    @Override
    public void refund(AdminRefundReq request) {
        PaymentReq req = new PaymentReq();
        req.setOrderId(request.getOrderId());
        req.setRefundReason(request.getRefundReason());
        paymentService.refundApply(req, OperateTypeEnum.ADMIN, AdminUtils.getCurrentAdmin().getAdminId());
    }

    @Override
    public void interfaceReturn(AdminReturnReq request) {

    }

    @Override
    public int delivery(List<OmsOrderDeliveryParam> deliveryParamList) {
        //批量发货
        int count = orderDao.delivery(deliveryParamList);
        //添加操作记录
        List<OmsOrderOperateHistory> operateHistoryList = deliveryParamList.stream()
                .map(omsOrderDeliveryParam -> {
                    OmsOrderOperateHistory history = new OmsOrderOperateHistory();
                    history.setOrderId(omsOrderDeliveryParam.getOrderId());
                    history.setCreateTime(LocalDateTime.now());
                    history.setOperateType("后台管理员");
                    history.setToOrderStatus(2);
                    history.setNote("完成发货");
                    return history;
                }).collect(Collectors.toList());
        orderOperateHistoryDao.insertList(operateHistoryList);
        return count;
    }

    @Override
    public int close(List<Long> ids, String note) {
        OmsOrder record = new OmsOrder();
        record.setStatus(4);
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria().andDeleteStatusEqualTo(0).andIdIn(ids);
        int count = orderMapper.updateByExampleSelective(record, example);
        List<OmsOrderOperateHistory> historyList = ids.stream().map(orderId -> {
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(orderId);
            history.setCreateTime(LocalDateTime.now());
            history.setOperateType("后台管理员");
            history.setToOrderStatus(4);
            history.setNote("订单关闭:" + note);
            return history;
        }).collect(Collectors.toList());
        orderOperateHistoryDao.insertList(historyList);
        return count;
    }

    @Override
    public int delete(List<Long> ids) {
        OmsOrder record = new OmsOrder();
        record.setDeleteStatus(1);
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria().andDeleteStatusEqualTo(0).andIdIn(ids);
        return orderMapper.updateByExampleSelective(record, example);
    }

    @Override
    public OmsOrderDetailResp detail(Long orderId) {
        OmsOrderDetail orderDetail = omsPortalOrderService.detail(orderId);
        OmsOrderDetailResp resp = OmsOrderDetailRespMapping.INSTANCE.convertTo(orderDetail);
        List<OmsOrderOperateHistory> orderOperateHistories = orderOperateHistoryMapper.selectList(new QueryWrapper<OmsOrderOperateHistory>()
                .eq("order_id", orderId).orderByDesc("create_time"));
        resp.setHistoryList(OrderOperateHistoryRespMapping.INSTANCE.convertTo(orderOperateHistories));
        return resp;
    }

    @Override
    public int updateReceiverInfo(OmsReceiverInfoParam receiverInfoParam) {
        OmsOrder order = new OmsOrder();
        order.setId(receiverInfoParam.getOrderId());
        order.setReceiverName(receiverInfoParam.getReceiverName());
        order.setReceiverPhone(receiverInfoParam.getReceiverPhone());
        order.setReceiverPostCode(receiverInfoParam.getReceiverPostCode());
        order.setReceiverDetailAddress(receiverInfoParam.getReceiverDetailAddress());
        order.setReceiverProvince(receiverInfoParam.getReceiverProvince());
        order.setReceiverCity(receiverInfoParam.getReceiverCity());
        order.setReceiverRegion(receiverInfoParam.getReceiverRegion());
        order.setModifyTime(LocalDateTime.now());
        int count = orderMapper.updateByPrimaryKeySelective(order);
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(receiverInfoParam.getOrderId());
        history.setCreateTime(LocalDateTime.now());
        history.setOperateType("后台管理员");
        history.setToOrderStatus(receiverInfoParam.getStatus());
        history.setNote("修改收货人信息");
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    @Override
    public int updateMoneyInfo(OmsMoneyInfoParam moneyInfoParam) {
        OmsOrder order = new OmsOrder();
        order.setId(moneyInfoParam.getOrderId());
        order.setFreightAmount(moneyInfoParam.getFreightAmount());
        order.setDiscountAmount(moneyInfoParam.getDiscountAmount());
        order.setModifyTime(LocalDateTime.now());
        int count = orderMapper.updateByPrimaryKeySelective(order);
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(moneyInfoParam.getOrderId());
        history.setCreateTime(LocalDateTime.now());
        history.setOperateType("后台管理员");
        history.setToOrderStatus(moneyInfoParam.getStatus());
        history.setNote("修改费用信息");
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    @Override
    public int updateNote(Long id, String note, Integer status) {
        OmsOrder order = new OmsOrder();
        order.setId(id);
        order.setNote(note);
        order.setModifyTime(LocalDateTime.now());
        int count = orderMapper.updateByPrimaryKeySelective(order);
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(id);
        history.setCreateTime(LocalDateTime.now());
        history.setOperateType("后台管理员");
        history.setToOrderStatus(status);
        history.setNote("修改备注信息：" + note);
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    @Override
    public OmsOrderDetailResp getOrderDetail(Long orderId) {
        com.amumu.drama.common.modules.order.dto.OmsOrderDetail orderDetail = omsPortalOrderService.detail(orderId);

        if (orderDetail == null) {
            return null;
        }
        return null;
    }
}
